package com.yunchang.springboot.scheduled.mwsfinance;

import com.yunchang.springboot.base.BaseService;
import com.yunchang.springboot.mapper.mws.finances.MwsFinancesFinancialReportMapper;
import com.yunchang.springboot.mapper.mwsreport.MwsPaymentMapper;
import com.yunchang.springboot.mapper.mwsutils.CwfzCurrencyCountryMapper;
import com.yunchang.springboot.mapper.mwsutils.CwfzFinancialSubjectsMapper;
import com.yunchang.springboot.mapper.mwsutils.CwfzMarketplaceCountryMapper;
import com.yunchang.springboot.models.mwsfinance.FPaymentSales;
import com.yunchang.springboot.models.mwsfinance.MwsFinancesFinancialReport;
import com.yunchang.springboot.models.mwsreportbean.MwsPayment;
import com.yunchang.springboot.utils.DateUtil;
import com.yunchang.springboot.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * payment销售订单  未完成
 */
@Component
@Configuration
@Service
@Slf4j
@EnableScheduling
public class FPaymentSalesScheduled extends BaseService {

    static final String TRANSACTION_TYPE = "Order";

    static final String FORM = "Payment";

    static final String TYPE = "Otherdefault";

    static final String COUNTRY_CODE = "GB";

    static final String COUNTRY_CODE_UK = "UK";

    static  Integer  LIMIT_VALUE = 10000;

    static String DOCUMENTS_ID = "HKD";

    /**
     * payment
     */
    private MwsPaymentMapper mwsPaymentMapper;

    @Autowired
    public void setMwsPaymentMapper(MwsPaymentMapper mwsPaymentMapper){
        this.mwsPaymentMapper = mwsPaymentMapper;
    }

    /**
     * finance原始数据
     */
    private MwsFinancesFinancialReportMapper mwsFinancesFinancialReportMapper;

    @Autowired
    public void setMwsFinancesFinancialReportMapper(MwsFinancesFinancialReportMapper mwsFinancesFinancialReportMapper) {
        this.mwsFinancesFinancialReportMapper = mwsFinancesFinancialReportMapper;
    }

    /**
     * 用于查询countryName的类
     */
    private CwfzMarketplaceCountryMapper cwfzMarketplaceCountryMapper;

    @Autowired
    public void setCwfzMarketplaceCountryMapper(CwfzMarketplaceCountryMapper cwfzMarketplaceCountryMapper){
        this.cwfzMarketplaceCountryMapper = cwfzMarketplaceCountryMapper;
    }

    /**
     * 获取country
     */
    private CwfzCurrencyCountryMapper cwfzCurrencyCountryMapper;

    @Autowired
    public void setCwfzCurrencyCountryMapper(CwfzCurrencyCountryMapper cwfzCurrencyCountryMapper) {
        this.cwfzCurrencyCountryMapper = cwfzCurrencyCountryMapper;
    }

    /**
     * 借贷关系
     */
    private CwfzFinancialSubjectsMapper cwfzFinancialSubjectsMapper;

    @Autowired
    public void setCwfzFinancialSubjectsMapper(CwfzFinancialSubjectsMapper cwfzFinancialSubjectsMapper) {
        this.cwfzFinancialSubjectsMapper = cwfzFinancialSubjectsMapper;
    }

//    @Scheduled(cron = "13 13 19 06 06 ?")
    public void getFPaymentSalesTest(){
        getFPaymentSales();
    }

//    @Scheduled(cron = "23 36 18 08 07 ?")
    @Transactional(rollbackFor = Exception.class)
    public void getFPaymentSales(){
//        Long mwsFinancesFinancialReportNum = mwsFinancesFinancialReportMapper.selectCountNumByFinanceStatusAndTransactionType(1, TRANSACTION_TYPE,null,null);
        List<MwsFinancesFinancialReport> mwsFinancesFinancialReportList = mwsFinancesFinancialReportMapper.selectByFinanceStatusAndTransactionType(1, TRANSACTION_TYPE,null,null);
        int mwsFinancesFinancialReportListNum= mwsFinancesFinancialReportList.size();
        log.info("销售订单原始数据的数量为："+mwsFinancesFinancialReportListNum);
        int forNum = 1;
        if(mwsFinancesFinancialReportListNum>LIMIT_VALUE){
            forNum += mwsFinancesFinancialReportListNum/LIMIT_VALUE;
            for(;forNum > 0;forNum--){
                log.info("剩余几次处理："+forNum);
                mwsFinancesFinancialReportList = mwsFinancesFinancialReportMapper.selectByFinanceStatusAndTransactionType(1, TRANSACTION_TYPE,LIMIT_VALUE,null);
                dateDispose(mwsFinancesFinancialReportList);
            }
        }else {
            dateDispose(mwsFinancesFinancialReportList);
        }
    }

    /**
     * 数据处理
     * @param mwsFinancesFinancialReportList
     */
    public void dateDispose(List<MwsFinancesFinancialReport> mwsFinancesFinancialReportList){
        if (null != mwsFinancesFinancialReportList && !mwsFinancesFinancialReportList.isEmpty()) {
            List<Object> fPaymentSalesList = new ArrayList<>();
            for(MwsFinancesFinancialReport mwsFinancesFinancialReport : mwsFinancesFinancialReportList){
                FPaymentSales fPaymentSales = new FPaymentSales();
                fPaymentSales.setIsManaulAdjust(1);
                fPaymentSales.setDocumentsId(DOCUMENTS_ID + UUIDUtil.getUUID());
                String postedDate = mwsFinancesFinancialReport.getPostedDate();
                fPaymentSales.setDate(postedDate);
                fPaymentSales.setSellerId(mwsFinancesFinancialReport.getSellerId());
                String countryCode = mwsFinancesFinancialReport.getCountryCode();
                String currency = mwsFinancesFinancialReport.getCurrency();
                fPaymentSales.setCurrency(currency);
                String marketplaceName = mwsFinancesFinancialReport.getMarketplaceName();
                countryCode = getCountry(countryCode, currency, marketplaceName);
                if(!StringUtils.isEmpty(countryCode)){
                    if(countryCode.equals(COUNTRY_CODE)){
                        countryCode = COUNTRY_CODE_UK;
                    }
                }
                fPaymentSales.setCountry(countryCode);
                String amazonOrderId = mwsFinancesFinancialReport.getAmazonOrderId();
                fPaymentSales.setOrderId(amazonOrderId);
                fPaymentSales.setMerchantOrderId(mwsFinancesFinancialReport.getMerchantOrderId());
                String type = mwsFinancesFinancialReport.getAmountDescription();
                fPaymentSales.setType(type);
                Double originalAmount = mwsFinancesFinancialReport.getAmount();
                fPaymentSales.setOriginalAmount(originalAmount);
                String transactionType = mwsFinancesFinancialReport.getTransactionType();
                Integer quantity;
                if(null != mwsFinancesFinancialReport.getQuantityPurchased()){
                    quantity = Math.toIntExact(mwsFinancesFinancialReport.getQuantityPurchased());
                }else {
                    quantity = getQuantity(transactionType,amazonOrderId,postedDate);
                }
                if(null  != quantity){
                    fPaymentSales.setQuantity(quantity);
                    fPaymentSales.setCostUnit(new BigDecimal(Math.abs(originalAmount)/quantity).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue());
                }
                String sku = mwsFinancesFinancialReport.getSku();
                if(StringUtils.isEmpty(sku)){
                    fPaymentSales.setSku(getSku(transactionType,amazonOrderId,postedDate));
                }else {
                    fPaymentSales.setSku(sku);
                }
                fPaymentSales.setAmount(Math.abs(originalAmount));
                Map<String, String> debitSubjectIdMap = getDebitSubjectId(originalAmount, type);
                if (null != debitSubjectIdMap && debitSubjectIdMap.containsKey("debitSubjectId2")) {
                    fPaymentSales.setIsManaulAdjust(2);
                    fPaymentSales.setDebitSubjectId(debitSubjectIdMap.get("debitSubjectId2"));
                } else {
                    fPaymentSales.setDebitSubjectId(debitSubjectIdMap.get("debitSubjectId"));
                }
                Map<String, String> creditSubjectIdMap = getCreditSubjectId(originalAmount, type);
                if (null != creditSubjectIdMap && creditSubjectIdMap.containsKey("creditSubjectId2")) {
                    fPaymentSales.setIsManaulAdjust(2);
                    fPaymentSales.setCreditSubjectId(creditSubjectIdMap.get("creditSubjectId2"));
                } else {
                    fPaymentSales.setCreditSubjectId(creditSubjectIdMap.get("creditSubjectId"));
                }
                fPaymentSales.setCreateTime(DateUtil.getTodayDate("yyyy-MM-dd HH:mm:ss"));
                fPaymentSales.setUpdateTime(DateUtil.getTodayDate("yyyy-MM-dd HH:mm:ss"));
                mwsFinancesFinancialReport.setFinanceStatus(2);
                fPaymentSalesList.add(fPaymentSales);
            }
            try {
                baseInsertList(fPaymentSalesList);
                log.info("已把全部数据插入完成，待更新状态");
                mwsFinancesFinancialReportMapper.updateMwsFinancesFinancialReportList(mwsFinancesFinancialReportList);
                log.info("状态已更新，齐活了");
            } catch (Exception e) {
                log.error("插入数据是出现错误，payment销售订单" + e);
                throw new RuntimeException("插入数据是出现错误，payment销售订单");
            }
        }else {
            log.info("未查询到对应的payment销售订单数据列表，时间为"+DateUtil.getTodayDate("yyyy-MM-dd HH:mm:ss"));
        }
    }

    /**
     * 根据mwsPayment对象中的字段判断其类型
     *
     * @param mwsPayment
     * @return
     */
    public Map<String,String> getTypeByMwsPayment(MwsPayment mwsPayment) {
        Map<String,String> returnMap = new HashMap<>(2);
        String type;
        if (null != mwsPayment.getPriceAmount()) {
            type = mwsPayment.getPriceType();
        } else if (null != mwsPayment.getItemRelatedFeeAmount()) {
            type = mwsPayment.getItemRelatedFeeType();
        } else if (null != mwsPayment.getMiscFeeAmount()) {
            type = "misc-fee";
        } else if (null != mwsPayment.getOtherFeeAmount()) {
            type = mwsPayment.getOtherFeeReasonDescription();
        } else if (null != mwsPayment.getPromotionAmount()) {
            type = mwsPayment.getPromotionType();
        } else if (null != mwsPayment.getDirectPaymentAmount()) {
            type = mwsPayment.getDirectPaymentType();
        } else if (null != mwsPayment.getOtherAmount()) {
            type = "other";
        } else {
            type = "";
            log.warn("根据mwsPayment的七个字段获取类型失败，未匹配到值！type为空,payment其他费用");
        }
        returnMap.put("type",type);
        return returnMap;
    }

    /**
     * 根据mwsPayment对象中的字段和type判断获取original_amount
     * @param mwsPayment
     * @param type
     * @return
     */
    public Double getOriginalAmount(MwsPayment mwsPayment,String type){
        Double originalAmount;
        return null;
    }

    /**
     * 获取country
     *
     * @param countryCode
     * @param currency
     * @return
     */
    public String getCountry(String countryCode, String currency, String marketplaceName) {
        String currencyValue = "EUR";
        if (StringUtils.isEmpty(countryCode)) {
            if (currency.equals(currencyValue)) {
                return cwfzMarketplaceCountryMapper.selectCountryByMarketplace(marketplaceName);
            } else {
                return cwfzCurrencyCountryMapper.getCountryPaymentByCurrency(currency);
            }
        } else {
            return countryCode;
        }
    }

    /**
     * 根据originalAmount和type获取debitSubjectId
     *
     * @param originalAmount
     * @param type
     * @return
     */
    public Map<String, String> getDebitSubjectId(Double originalAmount, String type) {
        String debitSubjectId;
        if (null != originalAmount) {
            if (originalAmount > 0) {
                debitSubjectId = cwfzFinancialSubjectsMapper.getDebitSubjectIdPositiveByTypeAndFormTransactionType(type, FORM, TRANSACTION_TYPE);
                if (StringUtils.isEmpty(debitSubjectId)) {
                    type = TYPE;
                    debitSubjectId = cwfzFinancialSubjectsMapper.getDebitSubjectIdPositiveByTypeAndFormTransactionType(type, FORM, TRANSACTION_TYPE);
                    String finalDebitSubjectId1 = debitSubjectId;
                    return new HashMap<String, String>(1) {{
                        put("debitSubjectId2", finalDebitSubjectId1);
                    }};
                } else {
                    String finalDebitSubjectId = debitSubjectId;
                    return new HashMap<String, String>(1) {{
                        put("debitSubjectId", finalDebitSubjectId);
                    }};
                }
            } else if (originalAmount < 0) {
                debitSubjectId = cwfzFinancialSubjectsMapper.getDebitSubjectIdNegativeByTypeAndFormTransactionType(type, FORM, TRANSACTION_TYPE);
                if (StringUtils.isEmpty(debitSubjectId)) {
                    type = TYPE;
                    debitSubjectId = cwfzFinancialSubjectsMapper.getDebitSubjectIdNegativeByTypeAndFormTransactionType(type, FORM, TRANSACTION_TYPE);
                    String finalDebitSubjectId1 = debitSubjectId;
                    return new HashMap<String, String>(1) {{
                        put("debitSubjectId2", finalDebitSubjectId1);
                    }};
                } else {
                    String finalDebitSubjectId = debitSubjectId;
                    return new HashMap<String, String>(1) {{
                        put("debitSubjectId", finalDebitSubjectId);
                    }};
                }
            } else {
                log.warn("根据originalAmount和type获取debitSubjectId,originalAmount等于0,payment其他费用");
            }
        } else {
            log.warn("根据originalAmount和type获取debitSubjectId,originalAmount为空,payment其他费用");
        }
        return null;
    }

    /**
     * 根据originalAmount和type获取creditSubjectId
     *
     * @param originalAmount
     * @param type
     * @return
     */
    public Map<String, String> getCreditSubjectId(Double originalAmount, String type) {
        String creditSubjectId;
        if (null != originalAmount) {
            if (originalAmount > 0) {
                creditSubjectId = cwfzFinancialSubjectsMapper.getCreditSubjectIdPositiveByTypeAndFormTransactionType(type, FORM, TRANSACTION_TYPE);
                if (StringUtils.isEmpty(creditSubjectId)) {
                    type = TYPE;
                    creditSubjectId = cwfzFinancialSubjectsMapper.getCreditSubjectIdPositiveByTypeAndFormTransactionType(type, FORM, TRANSACTION_TYPE);
                    String finalCreditSubjectId = creditSubjectId;
                    return new HashMap<String, String>(1) {{
                        put("creditSubjectId2", finalCreditSubjectId);
                    }};
                } else {
                    String finalCreditSubjectId1 = creditSubjectId;
                    return new HashMap<String, String>(1) {{
                        put("creditSubjectId", finalCreditSubjectId1);
                    }};
                }
            } else if (originalAmount < 0) {
                creditSubjectId = cwfzFinancialSubjectsMapper.getCreditSubjectIdNegativeByTypeAndFormTransactionType(type, FORM, TRANSACTION_TYPE);
                if (StringUtils.isEmpty(creditSubjectId)) {
                    type = TYPE;
                    creditSubjectId = cwfzFinancialSubjectsMapper.getCreditSubjectIdNegativeByTypeAndFormTransactionType(type, FORM, TRANSACTION_TYPE);
                    String finalCreditSubjectId = creditSubjectId;
                    return new HashMap<String, String>(1) {{
                        put("creditSubjectId2", finalCreditSubjectId);
                    }};
                } else {
                    String finalCreditSubjectId1 = creditSubjectId;
                    return new HashMap<String, String>(1) {{
                        put("creditSubjectId", finalCreditSubjectId1);
                    }};
                }
            } else {
                log.warn("根据originalAmount和type获取debitSubjectId,originalAmount为0,payment其他费用");
            }
        } else {
            log.warn("根据originalAmount和type获取debitSubjectId,originalAmount为空,payment其他费用");
        }
        return null;
    }

    /**
     *获取quantity
     * @param transactionType
     * @param amazonOrderId
     * @param postedDate
     * @return
     */
    public Integer getQuantity(String transactionType,String amazonOrderId,String postedDate){
        Integer quantity = null;
        if(!StringUtils.isEmpty(transactionType) && !StringUtils.isEmpty(amazonOrderId) && !StringUtils.isEmpty(postedDate)){
            Long quantity2 = mwsFinancesFinancialReportMapper.selectQuantityPurchasedByTransactionTypeAndAmazonOrderIdAndPostedDateAndQuantityPurchasedIsNotNull(transactionType, amazonOrderId, postedDate);
            if(null != quantity2){
                return  Math.toIntExact(quantity2);
            }else {
                log.info("获取到的quantity为空");
            }
        }else {
            log.info("获取quantity时，transactionType,amazonOrderId,postedDate三者中有为空的情况."+"transactionType:"+transactionType +"amazonOrderId:"+ amazonOrderId+"postedDate:"+postedDate);
        }
        return quantity;
    }

    /**
     * 获取sku
     * @param transactionType
     * @param amazonOrderId
     * @param postedDate
     * @return
     */
    public String getSku(String transactionType,String amazonOrderId,String postedDate){
        List<String> skuList;
        if(!StringUtils.isEmpty(transactionType) && !StringUtils.isEmpty(amazonOrderId) && !StringUtils.isEmpty(postedDate)) {
            skuList = mwsFinancesFinancialReportMapper.selectSkuByTransactionTypeAndAmazonOrderIdAndPostedDateAndQuantity(transactionType, amazonOrderId, postedDate);
            if(null != skuList && skuList.size() == 0){
                log.info("获取到的sku为空");
                return null;
            }
            if(null != skuList && skuList.size()>1){
                log.info("获取到的sku有多个");
                return null;
            }
            if(null != skuList && skuList.size() == 1){
                return skuList.get(0);
            }
        }else {
            log.info("获取sku时，transactionType,amazonOrderId,postedDate三者中有为空的情况."+"transactionType:"+transactionType +"amazonOrderId:"+ amazonOrderId+"postedDate:"+postedDate);
        }
        return null;
    }


}
